import React, { Component } from 'react';
import { Form, Select, Button, Input, Switch, Checkbox, Modal, Upload, Icon } from 'antd'
import { message } from "antd/lib/index";
import EditGroupType from './editGroupType.js'
import canDelDiv from "util/canDelDiv";
var fileData
const FormItem = Form.Item
const { TextArea } = Input
const Option = Select.Option
const formItemLayout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 14 },
}
const sendTypeOption = [
    {value: 1, name: '主题发送', disabled: false},
    {value: 2, name: '链接发送', disabled: false},
    {value: 3, name: '文件发送', disabled: false},
]
const sendTypeOptionFilter = [
    {value: 1, name: '主题发送', disabled: false},
    {value: 2, name: '链接发送', disabled: false},
    {value: 3, name: '文件发送', disabled: true},
]
const uploadProps = {
    name: 'file',
    action: '/snail/group/ddFileUpload',
    headers: {
        authorization: 'authorization-text',
    },
    onChange(info) {
        console.log(info)
        const { status, error, response } = info.file
        if ( status === "done" ) {
            console.log(fileData)
            fileData = info.fileList.map((item) => { return item.response.data[0]})
            message.info( response.message )
        } else if ( status === "removed" ) {
            fileData = info.fileList.map((item) => { return item.response.data[0]})
        }
        else if ( status === "error" ) {
            message.error( error.message )
        }
    },
};
class groupMsg extends Component {
    constructor(props){
        super(props)
        this.state = {
            groupType: [],
            groupMap: [],
            groupClassifyShow: false,
            filterTypeOneChecked: false,
            isFilterBtnShow: false,
            isGroupSortManageShow: false,
            sendType: sendTypeOption
        }
        this.handleSubmit = this.handleSubmit.bind(this)
        this.groupTypeChange = this.groupTypeChange.bind(this)
        this.addGroupHandle = this.addGroupHandle.bind(this)
        this.handleShow = this.handleShow.bind(this)
        this.getGroupType = this.getGroupType.bind(this)
    }
    handleSubmit(e) {
        e.preventDefault()
        let obj = this.props.form.getFieldsValue()
        let test = Object.values(obj)
        let { form } = this.props
        if (test.indexOf(undefined) !== -1) {
            message.error('请将各信息填写完整！')
        }else{
            let reqUrl = obj.sendType === 1 ? '/snail/group/groupDepartmentNotification' : obj.sendType === 2 ? '/snail/group/ddLinkUpload' : '/snail/group/ddFileUpSend'
            obj = obj.sendType === 3 ? Object.assign({}, obj, {data: fileData}) : obj
            if (obj.sendType === 3 && fileData.length === 0) {
                message.error('请先上传文件！')
                return
            }
            fetch( reqUrl , {
                method: "POST",
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(obj)
            }).then(function (response) {
                response.json().then(function (data) {
                    if (data.code == 200) {
                        message.info(data.message);
                        form.setFieldsValue({text: '', theme: '', linkPath: ''})
                    }
                })
            })
        }
    }
    handleShow() {
        this.setState({isGroupSortManageShow: true})
    }
    addGroupHandle(v){
        let hasNoTypeTwoGroup = this.state.groupMap.filter((item) => v.includes(item.id))
                                                    .some((item) => item.groupType !== 2)
        let sendType = hasNoTypeTwoGroup ? sendTypeOptionFilter : sendTypeOption
        hasNoTypeTwoGroup && this.props.form.setFieldsValue({ sendType: 1})
        this.setState({
            isFilterBtnShow: hasNoTypeTwoGroup,
            filterTypeOneChecked: false,
            sendType,
        })
    }
    groupTypeChange(value){
        const canSetGroup = this.state.groupType.find((item) => {return item.name === value}).group.map((item) => item.id)
        this.props.form.setFieldsValue({ids: canSetGroup})
    }
    getGroupType() {
       //获取群分类
        this.props.form.setFieldsValue({ sendType: 1 })
        fetch('/snail/group/findGroupClassification', {
            method: "GET",
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
        }).then(
            res => res.json()
        ).then(data => {
            let groupType = [], list = data.data
            for(let key in list){
                groupType.push({group: list[key], name: key})
            }
            this.setState({
                groupType
            })
        }) 
    }
    componentDidMount(){
        this.getGroupType()
        //获取所有群
        fetch('/snail/group/findAllGroup', {
            method: "GET",
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
        }).then(
            res => res.json()
        ).then(data => {
            const groupMap = data.data.pageInfo.list
            this.setState({
                groupMap
            })
        })
    }
    render(){
        let children = []
        const { getFieldDecorator, getFieldsValue, setFieldsValue } = this.props.form;
        const { groupMap, sendType } = this.state
        for (let i = 0; i < this.state.groupMap.length; i++) {
            children.push(<Option value={this.state.groupMap[i].id}>{this.state.groupMap[i].groupName}</Option>);
        }
        return (
            <div>
                <Form onSubmit={this.handleSubmit}>
                    <FormItem label="发送类型" {...formItemLayout}>
                        {getFieldDecorator('sendType')(
                            <Select placeholder="选择发送类型" onChange={(v) => {

                            }}>
                                {
                                    sendType.map((v) => {
                                        return (
                                            <Option value={v.value} disabled={v.disabled} key={v.value}>{v.name}</Option>
                                        )
                                    })
                                }
                            </Select>
                        )}
                    </FormItem>
                    <FormItem wrapperCol={{span:14, offset: 6}}>
                        <div style={{display: 'flex'}}>
                            <div style={{width: 44}}><Switch onChange={(value) => {this.setState({groupClassifyShow: value})}} /></div>
                            <div style={{flex: 1, paddingLeft: 20}}>{this.state.groupClassifyShow ? '隐藏群分类' : '显示群分类'}</div>
                        </div>
                    </FormItem>
                    {
                        this.state.groupClassifyShow &&
                        <FormItem label="群分类" {...formItemLayout}>
                            {getFieldDecorator('groupType', {
                                rules: [
                                    {require: true, message: '请选择群分类！'}
                                ],
                            })(
                                <Select placeholder="选择群分类" onChange={this.groupTypeChange}>
                                    {
                                        this.state.groupType && this.state.groupType.length ? this.state.groupType.map((item) => {
                                            return (
                                                <Option value={item.name} key={item.name}>{item.name}</Option>
                                            )
                                        }):null
                                    }
                                </Select>
                            )}
                        </FormItem>
                    }
                    <FormItem label="添加群组" {...formItemLayout}>
                        {getFieldDecorator('ids', {
                            initialValue: []
                        })(
                            <Select
                                mode="multiple"
                                placeholder="群组"
                                onChange={this.addGroupHandle}
                                optionFilterProp="children"
                            >
                                {children}
                            </Select>
                         )}
                    </FormItem>
                    <FormItem wrapperCol={{span:14, offset: 6}}>
                        <Checkbox defaultChecked={false} checked={this.props.form.getFieldsValue().ids.length === this.state.groupMap.length} onChange={(e) => {
                            const ids = e.target.checked ? this.state.groupMap.map((v) => v.id) : []
                            setFieldsValue({ ids })
                        }}>全选</Checkbox>
                        {
                            this.state.isFilterBtnShow && <Checkbox
                                checked={this.state.filterTypeOneChecked} onChange={(e) => {
                                let checked = e.target.checked
                                if (checked) {
                                    let ids = this.state.groupMap.filter((item) => getFieldsValue().ids.includes(item.id))
                                        .filter((item) => item.groupType === 2)
                                        .map((item) => item.id)
                                    setFieldsValue({ ids })
                                }
                                this.setState({
                                    filterTypeOneChecked: checked,
                                    sendType: sendTypeOption
                                })
                            }}>选择同步群组</Checkbox>
                        }
                    </FormItem>
                    {
                        getFieldsValue().sendType === 2 &&
                        <FormItem label="标题" {...formItemLayout}>
                            {getFieldDecorator('theme')(
                                <TextArea placeholder="请输入标题" autosize={{ minRows: 1, maxRows: 6 }} />
                            )}
                        </FormItem>
                    }
                    {
                        getFieldsValue().sendType === 2 &&
                        <FormItem label="链接" {...formItemLayout}>
                            {getFieldDecorator('linkPath')(
                                <TextArea placeholder="请输入链接" autosize={{ minRows: 2, maxRows: 6 }} />
                                )}
                        </FormItem>
                    }
                    {
                        (getFieldsValue().sendType === 1 || getFieldsValue().sendType === 2) && (<FormItem label="正文" {...formItemLayout}>
                            {getFieldDecorator('text')(
                                <TextArea placeholder="请输入正文" autosize={{ minRows: 2, maxRows: 6 }} />
                            )}
                        </FormItem>)
                    }
                    <FormItem wrapperCol={{span:14, offset: 6}}>
                        {
                            getFieldsValue().sendType === 3 &&
                            <div>

                                <Upload {...uploadProps} {...{data: {ids: getFieldsValue().ids}}}>
                                    <Button>
                                        <Icon type="upload" />文件上传
                                    </Button>
                                </Upload>
                                <span style={{fontSize: 13, color: '#ccc'}}>上传文件不得超过10M</span>
                            </div>
                        }
                    </FormItem>
                    <FormItem wrapperCol={{span:14, offset: 6}}>
                        <Button type="primary" htmlType="submit" style={{marginRight: 40}}>发送</Button>
                        <Button type="primary" onClick={this.handleShow}>编辑群分类</Button>
                    </FormItem>
                </Form>
                <Modal
                    title="群分类管理"
                    visible={this.state.isGroupSortManageShow}
                    onCancel={() => {
                        this.setState({isGroupSortManageShow: false})
                        this.getGroupType()
                    }}
                    footer={null}
                    width={800}
                >
                    <EditGroupType groupMap={groupMap}/>
                </Modal>
            </div>
        )
    }
}
export default Form.create()(groupMsg)